/*
 * xo-find.c
 *
 *  Created on: Aug 1, 2010
 *      Author: forhappy
 */

/*
 * Copyright (C) 2008 Carlos Garcia Campos  <carlosgc@gnome.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "xo-find.h"
#include "glib.h"
#include "gtk/gtk.h"

enum {
	TITLE_COLUMN,
	PAGE_COLUMN,
	STR_COLUMN,
	VISIBLE_COLUMN,
	N_COLUMNS
};

typedef struct {
	PopplerDocument *doc;

	GtkTreeModel    *model;
	GtkWidget       *entry;
	GtkWidget       *progress;

	gint             n_pages;
	gint             page_index;

	guint            idle_id;
} UtilFind;

static void
find_free (UtilFind *find)
{
	if (!find)
		return;

	if (find->idle_id > 0) {
		g_source_remove (find->idle_id);
		find->idle_id = 0;
	}

	if (find->doc) {
		g_object_unref (find->doc);
		find->doc = NULL;
	}

	if (find->model) {
		g_object_unref (find->model);
		find->model = NULL;
	}

	g_free (find);
}

static void
find_update_progress (UtilFind *find,
			  gint         scanned)
{
	gchar *str;

	str = g_strdup_printf ("Searching ... (%d%%)",
			       MIN (scanned * 100 / find->n_pages, 100));
	gtk_progress_bar_set_text (GTK_PROGRESS_BAR (find->progress), str);
	gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (find->progress),
				       MIN ((gdouble)scanned / find->n_pages, 1.0));
	g_free (str);
}

static gboolean
find_text (UtilFind *find)
{
	PopplerPage *page;
	GList       *matches;
	GTimer      *timer;
	gdouble char_length;

	page = poppler_document_get_page (find->doc, find->page_index);
	if (!page) {
		find->page_index++;
		return find->page_index < find->n_pages;
	}

	timer = g_timer_new ();
	matches = poppler_page_find_text (page, gtk_entry_get_text (GTK_ENTRY (find->entry)));
	g_timer_stop (timer);
	if (matches) {
		GtkTreeIter iter;
		gchar      *str;
		GList      *l;
		gint        n_match = 0;

		str = g_strdup_printf ("%d matches found on page %d in %.4f seconds",
				       g_list_length (matches), find->page_index + 1,
				       g_timer_elapsed (timer, NULL));

		gtk_tree_store_append (GTK_TREE_STORE (find->model), &iter, NULL);
		gtk_tree_store_set (GTK_TREE_STORE (find->model), &iter,
				    TITLE_COLUMN, str,
				    VISIBLE_COLUMN, FALSE,
				    -1);
		g_free (str);

		for (l = matches; l && l->data; l = g_list_next (l)) {
			char * string;
			PopplerRectangle *rect = (PopplerRectangle *)l->data;
			char_length=ABS(rect->x2-rect->x1);
			rect->x1=rect->x1-char_length/2;
			rect->x2=rect->x2+char_length/2;
			string=poppler_page_get_text(poppler_document_get_page (find->doc, find->page_index),
					POPPLER_SELECTION_WORD,rect);
			GtkTreeIter       iter_child;
			gchar *page;

			str = g_strdup_printf ("Match %d", ++n_match);
			page=g_strdup_printf("%d",find->page_index + 1);

			gtk_tree_store_append (GTK_TREE_STORE (find->model), &iter_child, &iter);
			gtk_tree_store_set (GTK_TREE_STORE (find->model), &iter_child,
					    TITLE_COLUMN, str,
					    PAGE_COLUMN, page,
					    STR_COLUMN,string,
					    VISIBLE_COLUMN, TRUE,
					    -1);
			g_free (str);
			g_free (page);
			g_free (rect);
		}
		g_list_free (matches);
	}

	g_timer_destroy (timer);
	g_object_unref (page);

	find->page_index++;
	find_update_progress (find, find->page_index);

	return find->page_index < find->n_pages;
}

static void
find_button_clicked (GtkButton   *button,
			 UtilFind *find)
{
	gtk_tree_store_clear (GTK_TREE_STORE (find->model));
	find->page_index = 0;
	find_update_progress (find, find->page_index);
	if (find->idle_id > 0)
		g_source_remove (find->idle_id);
	find->idle_id = g_idle_add ((GSourceFunc)find_text, find);
}

static void
find_button_sensitivity_cb (GtkWidget *button,
				GtkEntry  *entry)
{
	const gchar *text;

	text = gtk_entry_get_text (entry);
	gtk_widget_set_sensitive (button, text != NULL && text[0] != '\0');
}

GtkWidget *
create_find_widget (PopplerDocument *document)
{
	UtilFind     *find;
	GtkWidget       *vbox, *hbox;
	GtkWidget       *button;
	GtkWidget       *swindow;
	GtkWidget       *treeview;
	GtkCellRenderer *renderer;

	find = g_new0 (UtilFind, 1);

	find->doc = g_object_ref (document);

	find->n_pages = poppler_document_get_n_pages (document);

	vbox = gtk_vbox_new (FALSE, 12);

	hbox = gtk_hbox_new (FALSE, 6);

	find->entry = gtk_entry_new ();
	gtk_box_pack_start (GTK_BOX (hbox), find->entry, FALSE, TRUE, 0);
	gtk_widget_show (find->entry);

	find->progress = gtk_progress_bar_new ();
	gtk_progress_bar_set_ellipsize (GTK_PROGRESS_BAR (find->progress),
					PANGO_ELLIPSIZE_END);
	gtk_box_pack_start (GTK_BOX (hbox), find->progress, TRUE, TRUE, 0);
	gtk_widget_show (find->progress);

	button = gtk_button_new_with_label ("Find");
	gtk_widget_set_sensitive (button, FALSE);
	g_signal_connect (G_OBJECT (button), "clicked",
			  G_CALLBACK (find_button_clicked),
			  (gpointer)find);
	g_signal_connect_swapped (G_OBJECT (find->entry), "changed",
				  G_CALLBACK (find_button_sensitivity_cb),
				  (gpointer)button);
	gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0);
	gtk_widget_show (button);

	gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 6);
	gtk_widget_show (hbox);





	swindow = gtk_scrolled_window_new (NULL, NULL);
	gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (swindow),
					GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);

	find->model = GTK_TREE_MODEL (
		gtk_tree_store_new (N_COLUMNS,
				    G_TYPE_STRING,
				    G_TYPE_STRING, G_TYPE_STRING,
				    G_TYPE_BOOLEAN));
	treeview = gtk_tree_view_new_with_model (GTK_TREE_MODEL (find->model));
	gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (treeview), TRUE);
	gtk_tree_selection_set_mode (gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)),
							GTK_SELECTION_SINGLE);

	renderer = gtk_cell_renderer_text_new ();
	gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeview),
						     TITLE_COLUMN, "Matches",
						     renderer,
						     "text", TITLE_COLUMN,
						     NULL);

	renderer = gtk_cell_renderer_text_new ();
		gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeview),
								 PAGE_COLUMN, "Page",
								 renderer,
								 "text", PAGE_COLUMN,
								 "visible", VISIBLE_COLUMN,
								 NULL);

	renderer = gtk_cell_renderer_text_new ();
	gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (treeview),
							 STR_COLUMN, "Strings",
							 renderer,
							 "text", STR_COLUMN,
							 "visible", VISIBLE_COLUMN,
							 NULL);


	gtk_container_add (GTK_CONTAINER (swindow), treeview);
	gtk_widget_show (treeview);

	gtk_box_pack_start (GTK_BOX (vbox), swindow, TRUE, TRUE, 0);
	gtk_widget_show (swindow);

	g_object_weak_ref (G_OBJECT (vbox),
			   (GWeakNotify)find_free,
			   (gpointer)find);
	g_signal_connect(treeview,"row_activated",G_CALLBACK(on_findRow_activate),NULL);

	return vbox;
}
